package com.menghanjun.mhjresourcesharing.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.menghanjun.mhjresourcesharing.config.SendEmail;
import com.menghanjun.mhjresourcesharing.entity.TUser;
import com.menghanjun.mhjresourcesharing.mapper.TUserMapper;
import com.menghanjun.mhjresourcesharing.service.IMailService;
import com.menghanjun.mhjresourcesharing.service.ITUserService;
import com.menghanjun.mhjresourcesharing.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author menghanjun
 * @since 2023-08-11
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {

    @Autowired
    private TUserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private IMailService mailService;
    @Autowired
    private SendEmail sendEmail;

    private final static String WEBSTIE_NAME = "聊天GPT";//网站名称

    @Autowired
    private JwtUtils jwtUtils;



    /**
     * 增加用户
     * @param user
     */
    @Override
    public JsonResponseBody<?> addUser(TUser user) {
        try {
            QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name",user.getUserName());
            TUser tUser = userMapper.selectOne(queryWrapper);
            if(tUser != null){
                return new JsonResponseBody<>(JsonResponseStatus.USER_EXIST);
            }
            user.setUserId(CombinedIdGenerator.generateId());
            user.setCreatedAt(new Date());
            userMapper.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    @Transactional
    public JsonResponseBody<?> deleteUser(long id) {
        try {
            userMapper.deleteUser(id);
            stringRedisTemplate.delete("user"+id);//移除令牌
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResponseBody<>();
    }



    /**
     * 获取用户验证码
     * @param userid 用户id
     * @param email 目标邮箱
     * @param type 验证码类型
     * @return
     */
    @Override
    public JsonResponseBody<?> getUserCode(long userid, String email, String type) {
        try {
            if(ObjectUtils.isEmpty(email)||ObjectUtils.isEmpty(type)){
                return new JsonResponseBody<>(JsonResponseStatus.SEND_CODE_ERROR);
            }
            String username  = userMapper.selectOne(new QueryWrapper<TUser>().eq("user_id", userid)).getUserName();
            String key = "";
            String subject ="";
            String text = "";
            String code = Utils.generateVerificationCode(6);//获取6位数验证码
            if("editpassword".equals(type)){//修改密码
                key = "editpassword:" + userid;
                subject = WEBSTIE_NAME+"修改密码验证码";
                text = "这里是"+WEBSTIE_NAME+"网站，您的账号"+username+"正在修改密码！验证码为："+ code;
                text +="。验证码将在一分钟后失效，请及时使用！";
            }else if ("editemail".equals(type)) {
                key = "editemail:" + userid;
                subject = WEBSTIE_NAME+"修改邮箱验证码";
                text = "这里是"+WEBSTIE_NAME+"网站，您的账号"+username+"修改邮箱的验证码为："+ code;
                text +="。验证码将在一分钟后失效，请及时使用！";
            }
            boolean codeisExist = this.isCodeisExist(key);
            if (codeisExist) {//验证码已经存在
                return new JsonResponseBody<>(JsonResponseStatus.REPEAT_GET_CODE);
            }
            mailService.sendEmail(sendEmail.getUsername(),email,subject,text);//发送验证码
            stringRedisTemplate.opsForValue().set(key,code,1, TimeUnit.MINUTES);//缓存验证码
        }catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.SEND_CODE_ERROR);
        }
        return new JsonResponseBody<>();
    }

    /**
     * 修改密码
     * @param userid
     * @param code
     * @param password
     * @return
     */
    @Override
    public JsonResponseBody<?> editUserPassWord(long userid, int code, String password) {
        try {
            if(!ObjectUtils.isEmpty(userid)&&!ObjectUtils.isEmpty(code)&&!ObjectUtils.isEmpty(password)){
                String rediscode = stringRedisTemplate.opsForValue().get("editpassword:" + userid);
                if(ObjectUtils.isEmpty(rediscode)){
                    return new JsonResponseBody<>(JsonResponseStatus.CODE_NULL);
                }
                if(Integer.parseInt(rediscode)==code){
                    userMapper.editUserPassWord(userid,password);
                }else{
                    return new JsonResponseBody<>(JsonResponseStatus.CODE_ERRER);
                }
                //修改完毕删除验证码
                stringRedisTemplate.delete("editpassword:" + userid);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }

    /**
     * 更改用户邮箱
     * @param userid
     * @param code
     * @param email
     * @return
     */
    @Override
    public JsonResponseBody<?> editUserEmail(long userid, int code, String email) {
        try {
            if(!ObjectUtils.isEmpty(userid)&&!ObjectUtils.isEmpty(code)&&!ObjectUtils.isEmpty(email)){
                String rediscode = stringRedisTemplate.opsForValue().get("editemail:" + userid);
                if(ObjectUtils.isEmpty(rediscode)){
                    return new JsonResponseBody<>(JsonResponseStatus.CODE_NULL);
                }
                if(Integer.parseInt(rediscode)==code){
                    userMapper.editUserEmail(userid,email);
                }else{
                    return new JsonResponseBody<>(JsonResponseStatus.CODE_ERRER);
                }
                //修改完毕删除验证码
                stringRedisTemplate.delete("editemail:" + userid);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }

    @Override
    public boolean verifyAccountExpiration(String userid) {
        return this.isCodeisExist("user"+userid);
    }


    /**
     * 判断用户验证码是否存在
     * @return
     */
    private boolean isCodeisExist(String key){
        try {
            Object rediscode = stringRedisTemplate.opsForValue().get(key);
            if(rediscode == null){//不存在
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }


    /**
     * 获取用户列表
     * @param user
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public JsonResponseBody<?> getUserList(TUser user, int pageNo, int pageSize) {
        try {
            if(!ObjectUtils.isEmpty(user)){
                int offset = (pageNo - 1) * pageSize;
                List<TUser> list = userMapper.getUserList(user,offset,pageSize);
                QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
                if(!ObjectUtils.isEmpty(user.getUserName())){
                    queryWrapper.like("user_name",user.getUserName());
                }
                if(!ObjectUtils.isEmpty(user.getUserId())){
                    queryWrapper.like("user_id",user.getUserId());
                }
                if(!ObjectUtils.isEmpty(user.getEmail())){
                    queryWrapper.like("email",user.getEmail());
                }
                int pageToltal = userMapper.selectCount(queryWrapper);
                return new JsonResponseBody<>(list,pageToltal);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>(JsonResponseStatus.ERORR);
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public JsonResponseBody<?> userLogin(TUser user) {
        try {
            if(ObjectUtils.isEmpty(user.getUserName())||ObjectUtils.isEmpty(user.getPassword())){
                return new JsonResponseBody<>(JsonResponseStatus.MOBILE_OR_PWD_NULL);
            }
            QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name",user.getUserName());
            TUser tUser = userMapper.selectOne(queryWrapper);
            if(!ObjectUtils.isEmpty(tUser)){
                if(tUser.getUserStatus().equals("N")){//说明账号已过期
                    return new JsonResponseBody<>(JsonResponseStatus.TOKEN_ENPTY);
                }
                if(!MD5Utils.inputPassToFormpass(tUser.getPassword()).equals(user.getPassword())){
                    return new JsonResponseBody<>(JsonResponseStatus.PWD_ERORR);
                }
                JSONObject jwtjson  = new JSONObject();//用于储存要放到jwt中的信息
                jwtjson.put("userid",tUser.getUserId() + "");
                String logindate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                jwtjson.put("logindate",logindate);
                jwtjson.put("role",tUser.getRole());
                String tokenJWT = jwtUtils.generateToken(jwtjson.toJSONString());
                String key = "user"+tUser.getUserId();
                stringRedisTemplate.opsForValue().set(key,tokenJWT);
                stringRedisTemplate.expire(key, 7, TimeUnit.DAYS);//设置令牌过期时间为7天
                JSONObject result = new JSONObject();
                result.put("username",tUser.getUserName());
                result.put("userid",tUser.getUserId()+"");
                result.put("role",tUser.getRole());
                result.put("token",tokenJWT);
                return new JsonResponseBody<>(result.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.USER_NULL);
        }
        return new JsonResponseBody<>(JsonResponseStatus.USER_NULL);
    }

    /**
     * 根据UserID获取用户信息
     * @param userId
     * @return
     */
    @Override
    public JsonResponseBody<?> getUserById(long userId) {
        try {
            QueryWrapper<TUser> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            TUser tUser = userMapper.selectOne(wrapper);
            if(tUser!=null){
                //身份和密码不穿到前端
                tUser.setRole(null);
                tUser.setPassword(null);
                return new JsonResponseBody<>(tUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>(JsonResponseStatus.ERORR);
    }

    /**
     * 退出登录
     * @param userId
     * @return
     */
    @Override
    public JsonResponseBody<?> exitLogin(long userId) {
        try {
            stringRedisTemplate.delete("user"+userId);//移除令牌
            return new JsonResponseBody<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
    }

    @Override
    public JsonResponseBody<?> getUserByIdAdmin(long userId) {
        try {
            QueryWrapper<TUser> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            TUser tUser = userMapper.selectOne(wrapper);
            return new JsonResponseBody<>(tUser);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
    }

    /**
     * 编辑用户
     * @param user
     * @return
     */
    @Override
    public JsonResponseBody<?> editUser(TUser user) {
        try {
            if(!ObjectUtils.isEmpty(user.getUserId())){
                stringRedisTemplate.delete("user"+user.getUserId());//删除用户权限缓存
                userMapper.editUser(user);
                return new JsonResponseBody<>();
            }else{
                return new JsonResponseBody<>(JsonResponseStatus.ERORR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
    }


}
